package com.ciwong.epaper.modules.epaper.ui.newlistenspeak;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.ui.SelectQuestionDialog;
import com.ciwong.epaper.modules.epaper.util.HomeListener;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.CWDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * date :2018/5/3
 * author: loco
 * description:
 * version:
 * email: lzh838330255@163.com
 */

public class BaseConversationActivity extends BaseActivity {

    public ResourceDetail mResourceDetail;
    public int mLsMode;
    public int mBigQuesIndex = 0;
    public int mQuesTotalIndex = 0;
    public int mTotalCount = 0;
    protected int bigQuesIndex;
    protected int totalQuesIndex;
    protected String quesNo;
    public String mUuid;
    protected String mTitle;
    public List<ResourceDetail> mIsDoRecords;
    public Activity mActivity = this;
    public Context mContext = this;
    public ArrayList<LswAnswer> mLswAnswerList = new ArrayList<>();//答案集合
    public ArrayList<LswAnswer> mHasDoneAnswers = null;//重做页面携带过来的答案集合

    protected boolean mIsShowRecordsTips;
    public boolean mIsPlayStartExamAduio;

    protected TextView tx_record_continue_tips;
    public boolean isShowTime = true; //间隔时间内不需要显示倒计时
    protected final int MSG_DISMISS_NET_TIPS = 107;
    public boolean isReadBigQuestionStem = true;
    public boolean isStopHandle = false;
    public Handler mRecorderHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case ListenSpeakUtil.HandlerWhat.PLAY_SOUND:// 播放声音
                    isShowTime = true;
                    if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                        try {
                            AudioPlayer.getInstance().play(msg.obj.toString());
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                if (mMediaPlayer != null) {
                                    try {
                                        PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                        if (params != null) {
                                            mMediaPlayer.setPlaybackParams(params);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case MSG_DISMISS_NET_TIPS:
                    Animation animation2 = AnimationUtils.loadAnimation(mContext, R.anim.slide_up2);
                    animation2.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            tx_record_continue_tips.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    tx_record_continue_tips.startAnimation(animation2);

                    break;
                default:
                    break;
            }
            return true;
        }
    });


    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        if (intent != null) {
            mTitle = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
            mIsDoRecords = (List<ResourceDetail>) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DO_RECORDS);
            mResourceDetail = (ResourceDetail) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_QUE_ITEM);
            mLsMode = intent.getIntExtra(IntentFlag.INTENT_FLAG_LISTEN_MODE, 0);
            mBigQuesIndex = intent.getIntExtra(IntentFlag.INTENT_FLAG_CUR_NO, 0);
            mQuesTotalIndex = intent.getIntExtra(IntentFlag.INTENT_TOTAL_INDEX,0);
            mIsShowRecordsTips = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_IS_SHOW, false);
            mIsPlayStartExamAduio = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_IS_PLAY_STAET, false);
            mTotalCount = intent.getIntExtra(IntentFlag.INTENT_FLAG_TOTAL_NUM, 0);
            mHasDoneAnswers = (ArrayList<LswAnswer>) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_ANSWERS);
            mUuid = intent.getStringExtra(IntentFlag.INTENT_FLAG_UUID);
        }

    }

    @Override
    protected int setView() {
        return 0;
    }

    @Override
    protected void findViews() {
        tx_record_continue_tips = (TextView) findViewById(R.id.tx_record_continue_tips);
    }

    @Override
    protected void initEvent() {
        registListenerHome();
//        createPhoneListener();//监听电话
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                dealBack();
            }
        });
        initRightButton();
    }

    @Override
    protected void init() {
        setTitleText(mTitle);
        showRecorderTips(mIsShowRecordsTips);
        isReadBigQuestionStem = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + getUserInfoBase().getUserId(), true);
    }

    @Override
    protected void loadData() {
    }

    @Override
    public void onBackPressed() {

        dealBack();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台
            //全局变量isActive = false 记录当前已经进入后台
            if (mLsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                setResult(RESULT_CANCELED);
                finish();
            } else {
                setResultAnswer(getConversitionAnswer(), mBigQuesIndex, true, false, false,totalQuesIndex);
            }
        }
        Log.d(TAG, "###############onStop##################");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    protected ArrayList<LswAnswer> getConversitionAnswer() {
        return mLswAnswerList;
    }

    /**
     * @param lswAnswers
     * @param jumpBigIndext
     * @param isBackButton
     * @param isCompleteButtonClick 是否点击了完成按钮，true的话要跳到提交页面
     * @param isQuestionComplete    是否走完该题流程
     */
    public void setResultAnswer(ArrayList<LswAnswer> lswAnswers, int jumpBigIndext, boolean isBackButton, boolean isCompleteButtonClick, boolean isQuestionComplete,int mtotalQuesIndex) {
        isStopHandle = true;
        AudioPlayer.getInstance().stop();
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_ANSWERS, lswAnswers);
        intent.putExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_NEXT_BIGINDEX, jumpBigIndext);
        intent.putExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_TOTAL_INDEX,mtotalQuesIndex);
        intent.putExtra(IntentFlag.INTENT_FLAG_FROM_BACK_BUTTON, isBackButton);
        intent.putExtra(IntentFlag.INTENT_FLAG_FROM_COMPLETED_BUTTON, isCompleteButtonClick);
        intent.putExtra(IntentFlag.INTENT_FLAG_FROM_COMPLETED_QUESTION, isQuestionComplete);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 返回
     */
    protected void dealBack() {
        if (mLsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
            setResult(RESULT_CANCELED);
            finish();
        } else {
            showConfirmEndDialog();
        }
    }

    private void initRightButton() {
        // 自主练习
        if (mLsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE) {
            setRightBtnBG(R.mipmap.nav_switch_question);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    // 更新时间
//                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                    //自主联系 选题 界面   回调 REQ_CODE_TO_SELECT_QUESTION
                    //resetIsDoRecord();
                    SelectQuestionDialog selectQuestionDialog = new SelectQuestionDialog(BaseConversationActivity.this, mIsDoRecords);
                    Window dialogWindow = selectQuestionDialog.getWindow();
                    //设置Dialog从窗体底部弹出
                    dialogWindow.setGravity(Gravity.BOTTOM);
                    WindowManager.LayoutParams lp = selectQuestionDialog.getWindow().getAttributes();
                    lp.width = DisplayUtils.getScreenWidth(getApplicationContext()); //设置宽度
                    selectQuestionDialog.getWindow().setAttributes(lp);
                    selectQuestionDialog.setCanceledOnTouchOutside(true);
                    selectQuestionDialog.setCancelable(true);
                    selectQuestionDialog.setOnSelectQuestionListener(new SelectQuestionDialog.OnSelectQuestionListener() {
                        @Override
                        public void onSelectQuestion(int index, boolean isCommit) {
                            if (!isCommit && index == mBigQuesIndex) {
                                return;
                            }
                            if (isCommit) {
                                index = mBigQuesIndex + 1;
                                setResultAnswer(getConversitionAnswer(), index, false, true, false,totalQuesIndex);
                            } else {
                                setResultAnswer(getConversitionAnswer(), index, false, false, false,totalQuesIndex);
                            }

                        }
                    });
                    selectQuestionDialog.show();
                }
            });
        }
    }

    /**
     * 退出提示框
     */
    protected void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_back_work);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                setResultAnswer(getConversitionAnswer(), mBigQuesIndex, true, false, false,totalQuesIndex);

                            }
                        })
                .show();
    }

    /**
     * 监听电话
     */
    protected void createPhoneListener() {
        try {
            TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new OnPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected class OnPhoneStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, TelephonyManager.CALL_STATE_RINGING);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }


    @Override
    public void onHomeKeyPressed() {
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, TelephonyManager.CALL_STATE_RINGING);
        setResult(RESULT_OK, intent);
        finish();
    }


    private void showRecorderTips(boolean isShow) {
        if (tx_record_continue_tips == null) return;
        if (isShow) {
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.slide_down2);
            tx_record_continue_tips.startAnimation(animation);
            tx_record_continue_tips.setVisibility(View.VISIBLE);
            mRecorderHandler.sendEmptyMessageDelayed(MSG_DISMISS_NET_TIPS, 3000);
        }
    }

    public boolean isLastQuestion(ResourceDetail resourceDetail, int mSmallQuesIndex) {
        boolean isLastQues = false;
        //当前层级是否有小题，小题是否遍历完，大题遍历
        List<Questions> smallQuesList = resourceDetail.getQuestions();
        if (smallQuesList == null) return isLastQues;
        // 有小题
        if (mSmallQuesIndex < smallQuesList.size() - 1) {// 下一小题
            mSmallQuesIndex++;
        } else {
            isLastQues = true;
        }


        if (mLsMode != ListenSpeakUtil.LsMode.RETRY_MODE && isLastQues) {
            if (mBigQuesIndex == mTotalCount - 1) {
                isLastQues = true;
            } else {
                isLastQues = false;
            }

        }

        return isLastQues;
    }
}
